package org.example.util;

import cn.hutool.core.convert.Convert;
import cn.hutool.http.HttpRequest;
import cn.hutool.json.JSONObject;
import org.example.config.ThirdAppConfig;
import org.example.config.ThirdAppTypeItemVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

@Component
public class WechatUtil {
    @Autowired
    public ThirdAppConfig thirdAppConfig;

    public ThirdAppTypeItemVo getWechartConfig(){
        return thirdAppConfig.getWechatEnterprise();
    }

    /**
     * 获得access_token
     *
     * @return
     * @throws Exception
     */
    public String getAppAccessToken(RedisUtil redisUtil) {
        try {
            String accessToken = String.valueOf(redisUtil.get("ACCESS_TOKEN"));
            if (oConvertUtils.isNotEmpty(accessToken)) {
                return accessToken;
            }
            ThirdAppTypeItemVo config = thirdAppConfig.getWechatEnterprise();
            String result = HttpRequest.get("https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid=" + config.getClientId() +
                    "&corpsecret=" + config.getClientSecret())
                    .execute().body();

            //组装拼接过程
            cn.hutool.json.JSONObject jsonObject = new JSONObject(result);
            if ("0".equals(jsonObject.get("errcode").toString())) {
                Integer expires_in = Convert.toInt(jsonObject.get("expires_in"));
                redisUtil.set("ACCESS_TOKEN", jsonObject.get("access_token").toString(), expires_in);
                return jsonObject.get("access_token").toString();
            }
        } catch (Exception ex) {
           ex.printStackTrace();
        }
        return null;
    }
}
